<template>
  <div class="bigbox">
    <div class="topbox">
      <el-form
        :model="form"
        ref="form"
        label-position="left"
        label-width="80px"
        onsubmit="return false"
      >
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="用电企业">
              <FilterSelect2
                v-model="bizOrgNo"
                :optionlist="companyList"
                :valuekey="{ name: 'name', value: 'id' }"
                @changeSelect="companyChange"
              ></FilterSelect2>
            </el-form-item>
          </el-col>
          <el-col :span="19" style="text-align: right">
            <el-form-item>
              <Twobtn @chaxun="chaxun" @chongzhi="chongzhi"></Twobtn>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="bodybox">
      <div class="titlebox">
        <div class="text"></div>
        <div style="flex: 1; text-align: right; margin-right: 10px">
          <el-button type="primary" size="small" @click="add"
            ><i class="el-icon-plus">新增</i></el-button
          >
        </div>
        <TopTile
          @command="command"
          @daochu="daochu"
          @shuaxin="shuaxin"
        ></TopTile>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        height="77vh"
        border
        ref="table"
        :size="iissize"
        :header-cell-style="{
          background: '#f5f5f5',
          'text-align': 'center'
        }"
      >
        <template slot="empty">
          <el-empty description="暂无数据"></el-empty>
        </template>
        <el-table-column type="index" align="center" label="序号" width="150">
        </el-table-column>
        <el-table-column prop="companyName" label="用电企业"> </el-table-column>
        <el-table-column prop="className" label="设备名称"> </el-table-column>
        <el-table-column align="center" prop="discoverTime" label="发现时间">
        </el-table-column>
        <el-table-column align="center" prop="discoverer" label="发现人">
        </el-table-column>
        <el-table-column prop="exceptionMessage" label="异常信息描述">
        </el-table-column>
        <el-table-column align="center" prop="telephone" label="联系电话">
        </el-table-column>
        <el-table-column width="150px" align="center" label="操作">
          <template slot-scope="scope">
            <div class="table-cz">
              <el-tooltip
                class="item"
                effect="dark"
                content="编辑"
                placement="top"
              >
                <i
                  style="
                    font-size: 14px;
                    color: rgb(64, 149, 229);
                    cursor: pointer;
                  "
                  class="el-icon-edit"
                  @click="updateRecord(scope.row)"
                ></i
              ></el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="删除"
                placement="top"
              >
                <i
                  style="font-size: 14px; color: red; cursor: pointer"
                  class="el-icon-delete"
                  @click="del(scope.row)"
                ></i
              ></el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="浏览"
                placement="top"
              >
                <i
                  style="
                    font-size: 14px;
                    color: rgb(64, 149, 229);
                    cursor: pointer;
                  "
                  class="el-icon-view"
                  @click="view(scope.row)"
                ></i
              ></el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <nt-dialog
        title="异常信息"
        :visible.sync="dialogVisible"
        v-if="dialogVisible"
        width="500px"
        @diaClose="diaClose"
      >
        <el-form
          ref="dialogForm"
          :rules="rules"
          :model="dialogForm"
          label-width="auto"
        >
          <el-row :gutter="10">
            <el-col :span="24">
              <el-form-item label="用电企业" prop="companyId">
                <FilterSelect2
                  v-model="dialogForm.companyId"
                  :optionlist="companyList"
                  :valuekey="{ name: 'name', value: 'id' }"
                ></FilterSelect2>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="设备" prop="classId">
                <el-select
                  v-model="dialogForm.classId"
                  placeholder="选择设备"
                  size="small"
                  style="width: 100%"
                  ref="selectReport"
                >
                  <el-option
                    class="option"
                    :label="MeterPoints.name"
                    :value="dialogForm.classId"
                    style="height: auto"
                  >
                    <el-tree
                      ref="tree"
                      :props="props"
                      :highlight-current="true"
                      :load="loadNodedevice"
                      lazy
                      @node-click="handleNodeClick"
                    >
                      <template slot-scope="{ node, data }">
                        <span
                          :style="{
                            cursor:
                              data.className == 'AirconditionMain' ||
                              data.className == 'CoolingTower' ||
                              data.className == 'Boiler' ||
                              data.className == 'FreezePump' ||
                              data.className == 'CoolingPump' ||
                              data.className == 'DraughtFanCoiler' ||
                              data.className == 'NewDraughtFan' ||
                              data.className == 'Lighting' ||
                              data.className == 'Socket' ||
                              data.className == 'Elevator' ||
                              data.className == 'Pump' ||
                              data.className == 'ExhaustFan' ||
                              data.className == 'ElectricCalorifier' ||
                              data.className == 'SpeElectricDevice' ||
                              data.className == 'ProElectricDevice' ||
                              data.className == 'LightingSocket' ||
                              data.className == 'RollingMillDevice' ||
                              data.className == 'Pipeline' ||
                              data.className == 'Heatingpump' ||
                              data.className == 'Watersuppump' ||
                              data.className == 'EcmEquip'
                                ? 'pointer'
                                : 'no-drop',
                            fontSize: '14px',
                            color: '#606266'
                          }"
                        >
                          {{ node.label }}</span
                        >
                      </template>
                    </el-tree>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="discoverer" label="发现人">
                <el-input v-model="dialogForm.discoverer"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="discoverTime" label="发现时间">
                <el-date-picker
                  v-model="dialogForm.discoverTime"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  style="width: 100%"
                  :default-value="new Date()"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="exceptionMessage" label="异常描述">
                <el-input
                  type="textarea"
                  rows="3"
                  resize="none"
                  v-model="dialogForm.exceptionMessage"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="附件">
                <el-upload
                  class="upload-demo"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :limit="1"
                  :on-change="onChange"
                  :on-remove="onRemove"
                  :auto-upload="false"
                  :file-list="fileList"
                >
                  <el-button class="upload"
                    ><i class="el-icon-plus"></i
                  ></el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <div style="margin-top: 10px; text-align: center">
            <span slot="footer" class="dialog-footer">
              <el-button @click="diaClose">取 消</el-button>
              <el-button type="primary" @click="submit">确 定</el-button>
            </span>
          </div>
        </el-form>
      </nt-dialog>
      <nt-dialog
        title="异常信息"
        :visible.sync="viewVisible"
        v-if="viewVisible"
        width="500px"
        @diaClose="diaClose"
      >
        <el-form
          ref="dialogForm"
          :rules="rules"
          :model="dialogForm"
          label-width="auto"
        >
          <el-row :gutter="10">
            <el-col :span="24">
              <el-form-item label="用电企业" prop="companyId">
                <el-select disabled v-model="dialogForm.companyId">
                  <el-option
                    v-for="item in companyList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="设备" prop="classId">
                <el-select
                  disabled
                  v-model="dialogForm.classId"
                  placeholder="选择设备"
                  size="small"
                  style="width: 100%"
                  ref="selectReport"
                >
                  <el-option
                    class="option"
                    :label="MeterPoints.name"
                    :value="dialogForm.classId"
                    style="height: auto"
                  >
                    <el-tree
                      ref="tree"
                      :props="props"
                      :highlight-current="true"
                      :load="loadNodedevice"
                      lazy
                      @node-click="handleNodeClick"
                    >
                      <template slot-scope="{ node, data }">
                        <span
                          :style="{
                            cursor:
                              data.className == 'AirconditionMain' ||
                              data.className == 'CoolingTower' ||
                              data.className == 'Boiler' ||
                              data.className == 'FreezePump' ||
                              data.className == 'CoolingPump' ||
                              data.className == 'DraughtFanCoiler' ||
                              data.className == 'NewDraughtFan' ||
                              data.className == 'Lighting' ||
                              data.className == 'Socket' ||
                              data.className == 'Elevator' ||
                              data.className == 'Pump' ||
                              data.className == 'ExhaustFan' ||
                              data.className == 'ElectricCalorifier' ||
                              data.className == 'SpeElectricDevice' ||
                              data.className == 'ProElectricDevice' ||
                              data.className == 'LightingSocket' ||
                              data.className == 'RollingMillDevice' ||
                              data.className == 'Pipeline' ||
                              data.className == 'Heatingpump' ||
                              data.className == 'Watersuppump' ||
                              data.className == 'EcmEquip'
                                ? 'pointer'
                                : 'no-drop',
                            fontSize: '14px',
                            color: '#606266'
                          }"
                        >
                          {{ node.label }}</span
                        >
                      </template>
                    </el-tree>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="discoverer" label="发现人">
                <el-input disabled v-model="dialogForm.discoverer"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="discoverTime" label="发现时间">
                <el-date-picker
                  v-model="dialogForm.discoverTime"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  style="width: 100%"
                  disabled
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="exceptionMessage" label="异常描述">
                <el-input
                  disabled
                  type="textarea"
                  rows="3"
                  resize="none"
                  v-model="dialogForm.exceptionMessage"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="附件">
                <div @click="downLoad" style="color: #46a0e8; cursor: pointer">
                  {{ dialogForm.maintenanceName }}
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <div style="margin-top: 10px; text-align: center">
            <span slot="footer" class="dialog-footer">
              <el-button @click="diaClose">取 消</el-button>
              <!-- <el-button type="primary" @click="submit">确 定</el-button> -->
            </span>
          </div>
        </el-form>
      </nt-dialog>
    </div>
  </div>
</template>

<script>
// import { saveAs } from 'file-saver'
import {
  addExceptionMessageApi,
  delExceptionMessageApi,
  editExceptionMessageApi,
  getCompanyListApi,
  getPageListApi
} from '@/api/energy-consumption/Equipment-energy/Abnormal-information'
import { exportexcel, downloadFile } from '@/utils/excel'
import { getgenjiedianapi, getzijidianapi } from '@/api/monitor'
import ntDialog from '@/components/nt-dialog.vue'
import dayjs from 'dayjs'
export default {
  components: { ntDialog },
  name: 'AbnormalInformation',
  data() {
    return {
      bizOrgNo: '',
      isEdit: 'add',
      MeterPoints: { name: '', id: '' },
      dialogVisible: false,
      viewVisible: false,
      form: {},
      rules: {
        classId: [
          {
            required: true,
            message: '请选择设备',
            trigger: 'change'
          }
        ],
        companyId: [
          {
            required: true,
            message: '请选择用电企业',
            trigger: 'change'
          }
        ],
        discoverTime: [
          {
            required: true,
            message: '请选择发现时间',
            trigger: 'change'
          }
        ],
        discoverer: [
          {
            required: true,
            message: '请输入发现人',
            trigger: 'blur'
          }
        ],
        exceptionMessage: [
          {
            required: true,
            message: '请输入异常信息',
            trigger: 'blur'
          }
        ]
      },
      dialogForm: {},
      isheight: 72,
      props: {
        label: 'name',
        children: 'children',
        isLeaf: 'leaf'
      },
      iissize: 'medium',
      loading: false,
      tableData: [],
      total: 0,
      pageobj: {
        _pageNo: 0,
        _pageSize: 10
      },
      companyList: [],
      fileList: []
    }
  },
  async created() {
    await this.getCompanyList()
    await this.getdatalist()
  },
  methods: {
    companyChange(val) {
      localStorage.setItem('companyId', val)
    },
    // 获取用电企业列表
    async getCompanyList() {
      const res = await getCompanyListApi({ companyId: this.bizOrgNo })
      console.log(res)
      this.companyList = res.data.list
      const companyId = +localStorage.getItem('companyId')
      if (companyId && this.companyList.find((i) => i.id == companyId)) {
        this.bizOrgNo = companyId
      } else {
        this.bizOrgNo = this.companyList[0].id
      }
    },
    // 初始化
    async getchushihua() {
      this.bizOrgNo = this.companyList[0].id
      localStorage.setItem('companyId', this.companyList[0].id)
    },
    // 获取数据
    async getdatalist() {
      this.loading = true
      const res = await getPageListApi({
        companyId: this.bizOrgNo
        // pageNo: this.pageobj._pageNo - 1,
        // pageSize: 10
      })
      console.log(res)
      this.tableData = res.data.list
      // this.total = res.data.totalCount
      console.log(this.total)
      this.loading = false
    },
    // 新增弹窗
    add() {
      this.isEdit = 'add'
      this.$set(this.dialogForm, 'companyId', this.companyList[0].id)
      this.$set(
        this.dialogForm,
        'discoverTime',
        dayjs().format('YYYY-MM-DD HH:mm:ss')
      )
      this.dialogVisible = true
    },
    async updateRecord(item) {
      console.log(item)
      this.isEdit = 'edit'
      this.$set(this.dialogForm, 'companyId', item.companyId)
      this.$set(this.dialogForm, 'classId', item.classId)
      this.$set(this.dialogForm, 'exceptionMessage', item.exceptionMessage)
      this.$set(this.dialogForm, 'discoverTime', item.discoverTime)
      this.$set(this.dialogForm, 'discoverer', item.discoverer)
      this.$set(this.dialogForm, 'id', item.id)
      this.$set(this.MeterPoints, 'name', item.className)
      if (item.maintenanceFile) {
        this.fileList.push({ name: item.maintenanceName })
        this.$set(this.dialogForm, 'maintenanceFile', item.maintenanceFile)
      }
      this.dialogVisible = true
    },
    async view(item) {
      console.log(item)
      this.isEdit = 'view'
      this.$set(this.dialogForm, 'companyId', item.companyId)
      this.$set(this.dialogForm, 'classId', item.classId)
      this.$set(this.dialogForm, 'exceptionMessage', item.exceptionMessage)
      this.$set(this.dialogForm, 'discoverTime', item.discoverTime)
      this.$set(this.dialogForm, 'discoverer', item.discoverer)
      this.$set(this.MeterPoints, 'name', item.className)
      this.$set(this.dialogForm, 'maintenanceName', item.maintenanceName)
      this.$set(this.dialogForm, 'maintenanceFile', item.maintenanceFile)
      this.viewVisible = true
    },
    downLoad() {
      downloadFile(
        this.dialogForm.maintenanceName,
        this.dialogForm.maintenanceFile
      )
    },
    onChange(file, fileList) {
      console.log(file)
      console.log(fileList)
      this.$set(this.dialogForm, 'maintenanceFile', file.raw)
      this.$set(this.dialogForm, 'maintenanceName', file.name)
      this.fileList = fileList
    },
    onRemove(file, fileList) {
      console.log(file)
      console.log(fileList)
      this.fileList = fileList
      this.$set(this.dialogForm, 'maintenanceFile', '')
      this.$set(this.dialogForm, 'maintenanceName', '')
    },
    // 删除
    async del(row) {
      this.$confirm('请确认是否删除该异常信息', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            const res = await delExceptionMessageApi({
              classId: row.classId,
              id: row.id
            })
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: '删除成功',
                duration: 2000
              })
              this.getdatalist()
            } else {
              this.$message({
                type: 'error',
                message: res.message,
                duration: 2000
              })
            }
          } catch (e) {
            console.log(e)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async submit() {
      console.log(this.fileList)
      await this.$refs.dialogForm.validate()
      const res =
        this.isEdit === 'add'
          ? await addExceptionMessageApi(this.dialogForm)
          : await editExceptionMessageApi(this.dialogForm)
      console.log(res)
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: this.isEdit === 'add' ? '新增成功' : '修改成功',
          duration: 2000
        })
        this.getdatalist()
        this.diaClose()
      } else {
        this.$message({
          type: 'error',
          message: res.message,
          duration: 2000
        })
      }
    },
    // 刷新列表
    shuaxin() {
      this.getdatalist()
      this.$message({
        type: 'success',
        message: '列表刷新成功',
        duration: 2000
      })
    },
    chaxun() {
      this.getdatalist()
    },
    // 树点击
    handleNodeClick(val) {
      if (
        val.className == 'AirconditionMain' ||
        val.className == 'CoolingTower' ||
        val.className == 'Boiler' ||
        val.className == 'FreezePump' ||
        val.className == 'CoolingPump' ||
        val.className == 'DraughtFanCoiler' ||
        val.className == 'NewDraughtFan' ||
        val.className == 'Lighting' ||
        val.className == 'Socket' ||
        val.className == 'Elevator' ||
        val.className == 'Pump' ||
        val.className == 'ExhaustFan' ||
        val.className == 'ElectricCalorifier' ||
        val.className == 'SpeElectricDevice' ||
        val.className == 'ProElectricDevice' ||
        val.className == 'LightingSocket' ||
        val.className == 'RollingMillDevice' ||
        val.className == 'Pipeline' ||
        val.className == 'Heatingpump' ||
        val.className == 'Watersuppump' ||
        val.className == 'EcmEquip'
      ) {
        this.$set(this.MeterPoints, 'name', val.name)
        this.$set(this.dialogForm, 'classId', val.id)
        this.$refs.selectReport.blur()
      }
    },
    // 设备树懒加载
    async loadNodedevice(node, resolve) {
      // const res = await getgenjiedianapi({ treeModel: 'MbmDeviceManageTree' })
      const res = await getgenjiedianapi({ treeModel: 'ENERGY_SET_TREE' })
      // const res = await getzijidianapi()
      const ress = await getzijidianapi(res.data.list[0])
      if (node.level === 0) {
        // 初始的级数（最顶层）
        return resolve(ress.data.list) // 最顶层数据渲染为region
      }
      if (node.level === 0) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 1) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 2) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 3) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 4) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 5) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      }
    },
    // 导出
    daochu() {
      exportexcel(
        '/ecm-microservice-biz/ecm/device/exception/message/export',
        { companyId: this.bizOrgNo },
        '设备异常信息'
      )
    },
    command(val) {
      if (val === '默认') {
        this.iissize = 'medium'
      } else if (val === '中等') {
        this.iissize = 'small'
      } else {
        this.iissize = 'mini'
      }
    },
    diaClose() {
      this.dialogVisible = false
      this.viewVisible = false
      this.MeterPoints = { name: '', id: '' }
      this.fileList = []
      this.dialogForm = {}
    },
    async chongzhi() {
      await this.getchushihua()
      this.getdatalist('')
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-upload-list {
  width: 90%;
}
::v-deep .upload-demo {
  display: flex;
}

.table-cz {
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.upload {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
}
.bigbox {
  display: flex;
  flex-direction: column;
  background-color: #f1f1f1;
  padding: 10px;
  height: 100%;
  .topbox {
    background-color: #fff;
    padding: 20px;
    box-sizing: border-box;
    height: 80px !important;
    width: 100% !important;
    // transition-property: all;
    // transition-duration: 0.2s;
  }
  .bodybox {
    flex: 1;
    background-color: #fff;
    margin-top: 10px;
    padding: 20px 20px 20px 20px;
    .titlebox {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
      .text {
        font-weight: bold;
        font-size: 18px;
      }
      .right {
        align-items: center;
        i {
          margin-left: 10px;
        }
      }
    }
    .fenye {
      margin-top: 15px;
      text-align: right;
    }
  }
}
</style>
